<!--
 * @Description: 编辑活动
 * @Author: DXV-RGWU-TUFH-RFCY-IEGMYY
 * @Date: 2021-07-03 11:41:05
 * @LastEditTime: 2023-05-26 15:04:30
 * @LastEditors: DXV-RGWU-TUFH-RFCY-IEGMYY
-->

<template>
  <div class="lb-system-banner-edit">
    <top-nav :title="navTitle" :isBack="true" />
    <div class="page-main">
      <el-form @submit.native.prevent :model="subForm" :rules="subFormRules" ref="subForm" label-width="130px">
        <el-form-item label="活动名称" prop="title">
          <el-input v-model="subForm.title" show-word-limit placeholder="请输入活动名称"></el-input>
        </el-form-item>
        <el-form-item label="副标题" prop="sub_title">
          <el-input v-model="subForm.sub_title" show-word-limit placeholder="请输入副标题"></el-input>
        </el-form-item>
        <!-- <el-form-item label="所属分类" prop="cate_id">
          <el-select v-model="subForm.cate_id" multiple collapse-tags filterable clearable placeholder="请选择">
            <el-option v-for="item in base_cate" :key="item.id" :label="item.title" :value="item.id"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="封面图" prop="cover">
          <lb-cover :fileList="subForm.cover" @selectedFiles="getCover"></lb-cover>
          <lb-tool-tips>图片建议尺寸: 400 * 400</lb-tool-tips>
        </el-form-item>

        <div style="display: flex;margin-top: 20px;" v-for="(v, i) in subForm.group" :key="i">
          <el-form-item label="分组" prop="group">
            <el-input v-model="v.title" maxlength="30" show-word-limit placeholder="请输入分组名称"></el-input>
          </el-form-item>
          <el-form-item label="活动价格" prop="group">
            <el-input v-model="v.price" placeholder="请输入活动价格">
              <template slot="append">元</template></el-input>
          </el-form-item>
          <el-form-item label="活动人数" prop="group">
            <el-input v-model="v.registration_num" placeholder="请输入活动人数">
              <template slot="append">人</template></el-input>
          </el-form-item>
          <el-button v-if="i == 0" type="primary" round @click="pushGroup"
            style="height: 44px;margin-left: 50px;">添加分组</el-button>
          <el-button v-else type="danger" round @click="deleteGroup(v,i)"
            style="height: 44px;margin-left: 50px;">删除</el-button>
        </div>

        <el-form-item label="搜集信息" prop="item_ids">
          <el-checkbox-group v-model="subForm.item_ids">
            <el-checkbox v-for="v in ItemList" :key="v.id" :label="v.id">{{ v.title }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <!-- <el-form-item label="物料费" prop="material_price">
          <el-input v-model="subForm.material_price" placeholder="请输入物料费">
            <template slot="append">元</template></el-input>
          <lb-tool-tips>活动过程中消耗的物料费，例如：一次性衣物，物料费不计入{{
            $t('action.attendantName')
          }}提成</lb-tool-tips>
        </el-form-item> -->
        <!-- <el-form-item label="虚拟销售量" prop="sale">
          <el-input v-model="subForm.sale" placeholder="请输入虚拟销售量">
            <template slot="append">人选择</template></el-input>
          <lb-tool-tips>该虚拟销售量=虚拟+实际销售量</lb-tool-tips>
        </el-form-item> -->
        <!-- <el-form-item label="活动时长" prop="time_long">
          <el-input v-model="subForm.time_long" placeholder="请输入活动时长">
            <template slot="append">分钟</template>
          </el-input>
          <lb-tool-tips>一次活动的时间段，一般为60分钟</lb-tool-tips>
        </el-form-item> -->
        <!-- <el-form-item label="分销返佣" prop="com_balance">
          <el-input v-model="subForm.com_balance" placeholder="请输入分销返佣">
            <template slot="append">%</template>
          </el-input>
          <lb-tool-tips>实际支付金额的百分比</lb-tool-tips>
        </el-form-item> -->
        <!-- <el-form-item label="排序值" prop="top">
          <el-input-number class="lb-input-number" :min="0" :controls="false" v-model="subForm.top"
            placeholder="请输入排序值"></el-input-number>
          <lb-tool-tips>值越大, 排序越靠前</lb-tool-tips>
        </el-form-item> -->
        <el-form-item label="活动日期" prop="birthday">
          <el-date-picker v-model="subForm.birthday" type="datetimerange" value-format="timestamp" range-separator="至"
            start-placeholder="开始日期" end-placeholder="结束日期" align="right">
          </el-date-picker>
        </el-form-item>
        <!-- <el-form-item label="活动时间" prop="time">
          <el-time-select placeholder="开始时间" v-model="subForm.start_time" :picker-options="{
            start: '00:00',
            step: '00:01',
            end: '24:00'
          }" style="width: 150px"></el-time-select>
          <block>至</block>
          <el-time-select placeholder="结束时间" v-model="subForm.end_time" :picker-options="{
            start: '00:00',
            step: '00:01',
            end: '24:00'
          }" style="width: 150px"></el-time-select>
          <lb-tool-tips>营业时间和入驻{{
            $t('action.attendantName')
          }}的工作时间设置一致</lb-tool-tips>
        </el-form-item> -->
        <el-form-item label="活动地址" prop="address">
          <el-input v-model="subForm.address" placeholder="请输入活动地址"></el-input>
          <div class="mt-md mb-md">
            <el-input v-model="subForm.lng" placeholder="请输入活动经度"></el-input>
          </div>
          <div>
            <el-input v-model="subForm.lat" placeholder="请输入活动纬度"></el-input>
            <lb-button type="primary" class="getLocation" plain style="margin-left: 10px"
              @click="showMap = true">获取经纬度</lb-button>
          </div>
        </el-form-item>
        <el-form-item label="活动介绍" prop="text">
          <lb-ueditor v-model="subForm.text" :destroy="true"></lb-ueditor>
        </el-form-item>

        <el-form-item>
          <lb-button type="primary" @click="submitForm" v-preventReClick>{{
            $t('action.submit')
          }}</lb-button>
          <lb-button @click="$router.back(-1)">{{
            $t('action.back')
          }}</lb-button>
        </el-form-item>
      </el-form>

      <el-dialog :title="'关联' + $t('action.attendantName')" :visible.sync="showDialog" width="800px" center>
        <el-form :inline="true" :model="searchForm" ref="searchForm" label-width="70px">
          <el-form-item label="输入查询" prop="name">
            <el-input v-model="searchForm.name" :placeholder="'请输入' + $t('action.attendantName') + '姓名/手机号'
              "></el-input>
          </el-form-item>
          <el-form-item>
            <lb-button size="medium" type="primary" icon="el-icon-search" style="margin-right: 5px"
              @click="getTableDataList(1)">{{ $t('action.search') }}</lb-button>
            <lb-button size="medium" icon="el-icon-refresh-left" style="margin-right: 5px"
              @click="resetForm('searchForm')">{{
                $t('action.reset') }}</lb-button>
          </el-form-item>
        </el-form>
        <el-table :data="tableData" ref="multipleTable" :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
          tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="id" :label="$t('action.attendantName') + 'ID'"></el-table-column>
          <el-table-column prop="work_img" :label="$t('action.attendantName') + '头像'">
            <template slot-scope="scope">
              <lb-image :src="scope.row.work_img" />
            </template>
          </el-table-column>
          <el-table-column prop="coach_name" :label="$t('action.attendantName') + '姓名'"></el-table-column>
          <el-table-column prop="mobile" label="手机号"></el-table-column>
        </el-table>
        <lb-page :batch="false" :page="searchForm.page" :pageSize="searchForm.limit" :total="total"
          @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange">
        </lb-page>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showDialog = false">取 消</el-button>
          <el-button type="primary" @click="handleDialogConfirm">确 定</el-button>
        </span>
      </el-dialog>
    </div>
    <lb-map :dialogVisible.sync="showMap" @selectedLatLng="getLatLng"></lb-map>
  </div>
</template>

<script>
export default {
  data() {
    let checkTime = (rule, value, callback) => {
      let { start_time: start, end_time: end } = this.subForm
      if (!start || !end) {
        callback(new Error(!start ? `请选择开始时间` : `请选择结束时间`))
      } else {
        callback()
      }
    }
    let checkAddress = (rule, value, callback) => {
      let isLng = /^[\-\+]?(0(\.\d{1,15})?|([1-9](\d)?)(\.\d{1,15})?|1[0-7]\d{1}(\.\d{1,15})?|180\.0{1,15})$/
      let isLat = /^[\-\+]?((0|([1-8]\d?))(\.\d{1,15})?|90(\.0{1,15})?)$/
      let { address, lat, lng } = this.subForm
      address = address ? address.replace(/(^\s*)|(\s*$)/g, '') : ''
      if (!address) {
        callback(new Error(`请输入门店地址`))
      } else if (!lng || !isLng.test(lng)) {
        let msg = !lng ? `请输入门店经度` : `请输入正确的经度`
        callback(new Error(msg))
      } else if (!lat || !isLat.test(lat)) {
        let msg = !lat ? `请输入门店纬度` : `请输入正确的纬度`
        callback(new Error(msg))
      } else {
        callback()
      }
    }
    return {
      showMap: false,
      navTitle: '',
      base_cate: [],
      subForm: {
        id: '',
        title: '',
        sub_title: '',
        cover: [],
        status: 1,
        birthday: "",
        address: '',
        lat: '',
        lng: '',
        start_time: "",
        end_time: "",
        group: [{
          title: '',
          price: '',
          registration_num: "",
        }],
        item_ids: []
      },
      subFormRules: {
        title: { required: true, type: 'string', message: '请输入活动名称', trigger: 'blur' },
        sub_title: { required: true, type: 'string', message: '请输入副标题', trigger: 'blur' },
        // cate_id: { required: true, type: 'array', message: '请选择所属分类', trigger: 'blur' },
        cover: { required: true, type: 'array', message: '请上传图片', trigger: ['blur', 'change'] },
        imgs: { required: true, type: 'array', message: '请上传图片', trigger: ['blur', 'change'] },
        group: { required: true, message: '请输入分组信息', trigger: 'blur' },
        // group_title: { required: true, type: 'string', message: '请输入分组名称', trigger: 'blur' },
        // price: { required: true, validator: this.$reg.isMoney, text: '活动价格', trigger: 'blur' },
        // registration_num: { required: true, type: 'number', message: '请输入人数', trigger: 'blur' },
        material_price: { required: true, validator: this.$reg.isMoney, text: '物料费', trigger: 'blur' },
        sale: { required: true, validator: this.$reg.isNum, trigger: 'blur' },
        time_long: { required: true, validator: this.$reg.isNum, reg_type: 2, trigger: 'blur' },
        com_balance: { required: true, validator: this.$reg.isPercent, text: '分销返佣', trigger: 'blur' },
        text: { required: true, type: 'string', message: '请输入项目介绍', trigger: 'blur' },
        explain: { required: true, type: 'string', message: '请输入禁忌说明', trigger: 'blur' },
        notice: { required: true, type: 'string', message: '请输入下单须知', trigger: 'blur' },
        top: { required: true, type: 'number', message: '请输入排序值', trigger: 'blur' },
        coach: { required: true, type: 'array', message: '请选择关联' + this.$t('action.attendantName'), trigger: 'blur' },
        birthday: { required: true, message: '请选择日期', trigger: 'blur' },
        item_ids: { type: 'array', required: true, message: '请至选择1个收集信息', trigger: 'change' },
        time: { required: true, validator: checkTime, trigger: 'blur' },
        address: { required: true, validator: checkAddress, trigger: ['blur', 'change'] }

      },
      searchForm: {
        page: 1,
        limit: 10,
        status: 2,
        name: ''
      },
      total: 0,
      loading: false,
      tableData: [],
      multipleSelection: [],
      showDialog: false,
      ItemList: [],
    }
  },
  async created() {
    let { id } = this.$route.query
    await this.getBaseInfo()
    this.activityItemList()
    if (id) {
      this.subForm.id = id
      this.getDetail(id)
    }
    this.navTitle = this.$t(id ? 'menu.ActivityEdit' : 'menu.ActivityAdd')
  },
  methods: {
    async activityItemList() {
      let { code, data } = await this.$api.service.activityItemList({
        page: 1,
        limit: 100,
      })
      if (code !== 200) return
      this.ItemList = data
    },
    deleteGroup(val,ind){
      // console.log(val,ind);
      this.subForm.group.splice(ind, 1);
      console.log( this.subForm);
      
    },
    pushGroup() {
      this.subForm.group.push({
        title: '',
        price: '',
        registration_num: "",
        id: 0
      })
    },
    getLatLng(latLng) {
      this.subForm.lat = latLng.lat
      this.subForm.lng = latLng.lng
    },
    async getBaseInfo() {
      let { data } = await this.$api.service.cateSelect()
      this.base_cate = data
    },
    getCover(img) {
      this.subForm.cover = img
    },
    getBannerList(imgs) {
      this.subForm.imgs.push(...imgs)
    },
    /**
     * @name: 详情
     * @param {*} id
     */
    async getDetail(id) {
      let { code, data } = await this.$api.service.activityInfo({ id })
      if (code !== 200) return
      data.cover = [{ url: data.cover }]


      data.item_ids = data.item_ids.split(",").map(Number);


      for (let key in this.subForm) {
        this.subForm[key] = data[key]
      }
      // this.subForm.birthday = [data.start_time * 1000,data.end_time * 1000]
      const targetDate1 = new Date(data.start_time);
      const targetDate2 = new Date(data.end_time);
      this.subForm.birthday = [Math.floor(targetDate1.getTime()), Math.floor(targetDate2.getTime())]
    },
    async toShowDialog() {
      this.searchForm.name = ''
      await this.getTableDataList()
      this.showDialog = !this.showDialog
    },
    resetForm(form) {
      this.$refs[form].resetFields()
      this.getTableDataList(1)
    },
    handleSizeChange(val) {
      this.searchForm.limit = val
      this.handleCurrentChange(1)
    },
    handleCurrentChange(val) {
      this.searchForm.page = val
      this.getTableDataList()
    },
    async getTableDataList(flag) {
      if (flag) this.searchForm.page = 1
      this.tableData = []
      this.loading = true
      let { code, data } = await this.$api.technician.coachList(this.searchForm)
      this.loading = false
      if (code !== 200) return
      this.tableData = data.data
      this.total = data.total
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleDialogConfirm() {
      let coach = JSON.parse(JSON.stringify(this.subForm.coach))
      let arr1 = coach.length > 0 ? coach.map(item => { return item.id }) : []
      this.multipleSelection.map(item => {
        if (arr1.includes(item.id)) return
        coach.push(item)
      })
      this.subForm.coach = coach
      this.showDialog = false
    },
    confirmDel(id) {
      let index = this.subForm.coach.findIndex(item => {
        return item.id === id
      })
      this.subForm.coach.splice(index, 1)
    },
    /**
     * @name: 新增/编辑
     * @param {*}
     */
    submitForm() {
      let flag = true
      this.$refs['subForm'].validate(valid => {
        if (!valid) flag = false
      })
      if (flag) {
        let subForm = JSON.parse(JSON.stringify(this.subForm))
        subForm.cover = subForm.cover[0].url
        // subForm.imgs = subForm.imgs.map(item => {
        //   return item.url
        // })
        // let arr = subForm.coach.map(item => {
        //   return item.id
        // })
        // subForm.coach = arr

        subForm.item_ids = subForm.item_ids.join(',')
        subForm.start_time = subForm.birthday[0] / 1000
        subForm.end_time = subForm.birthday[1] / 1000
        this.$delete(subForm, 'birthday');
        let modelMethod = subForm.id ? 'activityUpdate' : 'activityAdd'
        this.$api.service[modelMethod](subForm).then(res => {
          if (res.code === 200) {
            this.$message.success(this.$t(subForm.id ? 'tips.successRev' : 'tips.successSub'))
            this.$router.back(-1)
          }
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.lb-system-banner-edit {
  width: 100%;

  .el-form {
    width: 100%;

    .el-select,
    .el-input-number,
    .el-input {
      width: 300px;
    }

    .el-textarea {
      width: 600px;
    }
  }
}
</style>
